<template>
    <div class="voice" @click="play()" :class="{'play':!playStatus,'pause':playStatus}">
        <span>语音播放</span>
        <img src="./icon/pause.png" v-if="playStatus">
        <img src="./icon/play.png" v-else>
        <!-- 播放器 -->
        <audio
            autoplay
            id="audio"
            preload="auto"
            :src="audioUrl2"
            @play="onPlay"
            @ended="onEnded"
            @pause="onPause">
        </audio>
    </div>
</template>

<script>
export default {
    props:["url"],
    data () {
        return {
            audioUrl2:"",  //语音的url地址
            playStatus:false,  //true正在播放，false暂停
        }
    },
    watch:{
        url(val){
            console.log('url改变了');
            this.playStatus = false;
        }
    },
    methods:{
        //点击事件
        play:function(){
            var oAudio = document.getElementById('audio');
            //新目标
            if(this.audioUrl2 != this.url){
                console.log('新目标');
                this.playStatus = true;
                this.audioUrl2 = this.url;
                oAudio.play();
            }
            else{
                //如果正在播放中，让它停止
                if(this.playStatus){
                    this.playStatus = false;
                    oAudio.pause();
                    this.audioUrl2 = "";
                }
                //如果已经暂停/停止，让它播放
                else{
                    this.playStatus = true;
                    this.audioUrl2 = this.url; //组件传递过来的url
                    oAudio.play();
                }
            }
        },
        //开始播放
        onPlay:function(res){
            this.playStatus = true;
        },
        //播放结束
        onEnded:function(res){
            this.playStatus = false;
        },
        //暂停播放
        onPause:function(res){
            this.playStatus = false;
        },
    },
    mounted(){
        console.log(this.obj);
    }
}
</script>

<style lang="scss" scoped>
    .voice{
        display: flex;
        align-items: center;
        width: 100px;
        cursor: pointer;
        img{
            width: 22px;
            margin-left: 6px;
        }
    }
    .play{
        span{
            color: $blue;
        }
    }
    .pause{
        span{
            color: $orange;
        }
    }
</style>
